package com.hrt.log;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.Layout;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

import com.btcode.log.ILog;
import com.btcode.log.ILogFactory;

public class MqMonitorLogFactory implements ILogFactory {

    private HashMap<String, ILog> logs = new HashMap<String, ILog>();

    @Override
    public ILog getLog(String name, String path) {

        if (!name.startsWith("com")) {
            name = "com." + name;
        }

        ILog oLogger = logs.get(name);

        if (oLogger != null) {
            return oLogger;
        }

        Logger myTest = Logger.getLogger(name);
        Layout layout = new PatternLayout("[%d{yyyy-MM-dd HH:mm:ss:SSS}] %m%n");

        File dir = new File(path);
        if (!dir.isDirectory()) {
            if (!dir.mkdirs()) {
                System.out.println("创建" + path + "目录失败");
            }
            else {
                System.out.println(path + "已存在");
            }
        }

        File logFile = new File(path + "/" + name + ".log");
        if (!logFile.exists()) {
            try {
                logFile.createNewFile();
            }
            catch (IOException e) {
                System.out.println(logFile.getPath() + "创建日志文件失败" + e.toString());
                System.out.println(e.getMessage());
                e.printStackTrace();
                return null;
            }
        }

        DailyRollingFileAppender appender = null;
        ConsoleAppender consoleAppender = null;
        try {
            appender = new DailyRollingFileAppender(layout, path + "/" + name + ".log", "'.'yyyy-MM-dd");
            appender.setAppend(true);
            appender.activateOptions();
            consoleAppender = new ConsoleAppender(layout, "System.out");
            consoleAppender.activateOptions();
        }
        catch (IOException e) {
            e.printStackTrace();
            return null;
        }

        myTest.addAppender(appender);
        myTest.addAppender(consoleAppender);

        Log4MQ l4j = new Log4MQ(myTest);

        logs.put(name, l4j);

        LogMonitor.getInstance().push(name, l4j);

        System.out.println("日志路径：" + path + "/" + name + ".log");

        return l4j;
    }
}
